package gpl.scotlandyard.fugitive.hint.result;

import gpl.scotlandyard.fugitive.hint.ApplicationManager;
import gpl.scotlandyard.fugitive.hint.R;
import gpl.scotlandyard.services.PathFinder;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class ResultActivity extends Activity implements PathFinder.Listener {

  public static final String ARG_PATH_FINDER = "ARG_PATH_FINDER";
  private PathFinder pathFinder;
  private PathResultGridAdapter listAdapter;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.result_activity);
    pathFinder = ApplicationManager.pull(ARG_PATH_FINDER, PathFinder.class);
    listAdapter = new PathResultGridAdapter(this, pathFinder);
    final GridView gridview = (GridView) findViewById(R.id.result_grid);
    gridview.setAdapter(listAdapter);
    ApplicationManager.execute(new Runnable() {
      @Override
      public void run() {
        pathFinder.performDiscover();
        gridview.setNumColumns(pathFinder.getLongestSafePathLength());
        updated();
      }
    });
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.result, menu);
    return true;
  }

  @Override
  public void updated() {
    runOnUiThread(new Runnable() {
      @Override
      public void run() {
        listAdapter.notifyDataSetChanged();
        TextView textView = (TextView) findViewById(R.id.result_title);
        textView.setText(getString(R.string.result_found_ways, pathFinder.getLongestSafePathsCount(), pathFinder.getLongestSafePathLength()));

        GridView gridView = (GridView) findViewById(R.id.result_grid);
        gridView.setVisibility(View.VISIBLE);

        ProgressBar progressBar = (ProgressBar) findViewById(R.id.result_progressBar);
        progressBar.setVisibility(View.GONE);
      }
    });
  }

}
